package common.server.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 对象序列化帮助类
 * @author Administrator
 * @version [版本号, 2017/11/20 0020]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class SerializeHelper {

    private static Logger logger = LoggerFactory.getLogger(SerializeHelper.class);

    private static final String TEMP_ENCODING = "ISO-8859-1";
    private static final String DEFAULT_ENCODING = "UTF-8";


    public static String serializeStr(Object object){
        String serStr = null;
        try {
            byte[] result = serialize(object);
            serStr = new String(result,TEMP_ENCODING);
            serStr = java.net.URLEncoder.encode(serStr, DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            logger.error("Failed to serializeStr", e);
        }
        return serStr;
    }

    /**
     * 序列化
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        byte[] result = null;
        if (object == null) {
            return new byte[0];
        }
        ByteArrayOutputStream byteStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            byteStream = new ByteArrayOutputStream(128);
                if (!(object instanceof Serializable)) {
                    throw new IllegalArgumentException(
                            SerializeHelper.class.getSimpleName()
                                    + " requires a Serializable payload "
                                    + "but received an object of type ["
                                    + object.getClass().getName() + "]");
                }
                objectOutputStream = new ObjectOutputStream(byteStream);
                objectOutputStream.writeObject(object);
                objectOutputStream.flush();
                result = byteStream.toByteArray();
        } catch (Exception ex) {
            logger.error("Failed to serialize", ex);
        } finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
                if (byteStream != null) {
                    byteStream.close();
                }
            } catch (IOException e) {
            }
        }
        return result;
    }

    /**
     * 反序列化
     * @param bytes
     * @return
     */
    public static Object deserialize(byte[] bytes) {
        Object result = null;
        if (isEmpty(bytes)) {
            return null;
        }
        ObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
            result = objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace() ;
            logger.error("Failed to deserialize Exception e:" + e);
        } finally {
            close(objectInputStream);
        }
        return result;
    }

    public static Object deserializeStr(String serStr){
        Object result = null;
        try {
            String deserStr = java.net.URLDecoder.decode(serStr, DEFAULT_ENCODING);
            result=  deserialize(deserStr.getBytes(TEMP_ENCODING));
        } catch (UnsupportedEncodingException e) {
            logger.error("Failed to deserializeStr", e);
        }
        return result;
    }

    /**
     *
     * @param in
     */
    private static  void close(ObjectInputStream in){
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }

    }

    private static boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }
}
